package com.seednia.module.core.xport;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import com.seednia.foundation.framework.dto.AbstractRecord;
import com.seednia.foundation.framework.service.IDataOrientedService;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.service.ServiceException;

/**
 * 
 * @author Young Suk Ahn
 *
 */
public abstract class AbstractImporter extends AbstractXporterBase implements IImporter {
	
	public abstract XportDataContainer importFrom(InputStream is, Map<String, Object> params) throws Exception;


	@Override
	public void importAppData(InputStream xmlInput, Map<String, Object> params)  throws ServiceException, XportException {
		int recordNum = 0;
		String currProcessorService = "";
		try {
			XportDataContainer dataContainer = importFrom(xmlInput, null);
			
			for (XportData xporData : dataContainer.getXportDataList()){
				currProcessorService = xporData.getProcessorServiceId();
				IDataOrientedService doSvc = (IDataOrientedService) ServiceContainer.getInstance().getById(currProcessorService);
				
				for (AbstractRecord record: xporData.getRecords()) {
					// TODO Check whether the record already exists using unique key
					doSvc.prepareReferencesAndInsert(null, record);
					recordNum++;
				}
			}
		} catch (Exception e) {
			throw new XportException("Exception while processing record #"+recordNum+" of service '"+currProcessorService+"': "+e, e);
		}
	}
	
	@Override
	public void importAppData(File file, Map<String, Object> params) throws ServiceException, IOException, XportException {
		InputStream is = new FileInputStream(file);
		importAppData(is, params);
		is.close();
	}
	

}
